dofile ("libKeyboard.lua")

TextBox = {}

tbx = 0
tby = 0

function TextBox.init (txb, x, y, larg, haut, mode, coul, coul_txt)
  local tb = tostring (txb)
  
  _G[tb] = {}
  
  _G[tb].x = x
  _G[tb].y = y
  
  _G[tb].larg = larg
  _G[tb].haut = haut
  
  _G[tb].x2 = _G[tb].x+_G[tb].larg
  _G[tb].y2 = _G[tb].y+_G[tb].haut
  
  _G[tb].mode = mode
  
  _G[tb].box = newBox (_G[tb].x, _G[tb].y, _G[tb].x2, _G[tb].y2)
  
  if coul ~= nil then _G[tb].col1 = coul else _G[tb].col1 = Color.new(31, 31, 31) end
  if coul_txt ~= nil then _G[tb].col2 = coul_txt else _G[tb].col2 = Color.new(0, 0, 0) end

  
  _G[tb].hasfocus = false
  
  _G[tb].k = tb..".keyboard"
  
  _G[tb].nb_fois = 0
  
  Keyboard.init (_G[tb].k, 18, 9*8)
end

function TextBox.draw (txb)
  local tb = tostring (txb)
  
  if Stylus.held then
    tbx = Stylus.X
    tby = Stylus.Y
    _G[tb].hasfocus = false
  end
  
  Keyboard.draw (_G[tb].k)
  
  if _G[tb].mode == 1 then
    Button.disable (_G[_G[tb].k].bts[55])
  elseif _G[tb].mode == 2 then
    Button.enable (_G[_G[tb].k].bts[55])
  end
  
  screen.drawFillRect (SCREEN_DOWN, _G[tb].x, _G[tb].y, _G[tb].x2, _G[tb].y2, _G[tb].col1)
  screen.drawRect (SCREEN_DOWN, _G[tb].x+1, _G[tb].y+1, _G[tb].x2, _G[tb].y2, c_gris)
  screen.drawRect (SCREEN_DOWN, _G[tb].x, _G[tb].y, _G[tb].x2, _G[tb].y2, _G[tb].col1)
  
  local txt = Keyboard.text (_G[tb].k)
local nb_suppor = math.floor(_G[tb].larg / 6)
nb_support = nb_suppor + _G[tb].nb_fois * nb_suppor
local nb_carac = string.len(txt) - _G[tb].nb_fois * nb_suppor + 1
local nb_cara = string.len(txt) - nb_suppor + 1

if nb_cara == nb_support then

_G[tb].nb_fois = _G[tb].nb_fois + 1

end

if string.len(txt) < nb_suppor then

  if _G[tb].hasfocus then
    screen.print (SCREEN_DOWN, _G[tb].x+3, _G[tb].y+3, txt.."|", _G[tb].col2)

  else 
    screen.print (SCREEN_DOWN, _G[tb].x+3, _G[tb].y+3, txt, _G[tb].col2)

  end

else

  if _G[tb].hasfocus then
    screen.print (SCREEN_DOWN, _G[tb].x+3, _G[tb].y+3, string.sub(txt, nb_cara).."|", _G[tb].col2)

  else 
    screen.print (SCREEN_DOWN, _G[tb].x+3, _G[tb].y+3, string.sub(txt, nb_cara), _G[tb].col2)

  end

end

  
  if Stylus.heldinBox (_G[tb].box, tbx, tby) then
    _G[tb].hasfocus = true

  end
  
  if Keyboard.isAnyKeyPressed (_G[tb].k) then
    _G[tb].hasfocus = true

  end

  
  _G[_G[tb].k].visible = _G[tb].hasfocus
end

function TextBox.focus (txb)
  local tb = tostring (txb)

  return _G[tb].hasfocus
end

function TextBox.text (txb)
  local tb = tostring (txb)
  
  return Keyboard.text (_G[tb].k)
end

function TextBox.clear (txb)
  local tb = tostring (txb)
  
  _G[tb] = nil
  
  tbx = nil
  tby = nil
  
  Keyboard.clear (_G[tb].k)
end
